package com.bodacn.keypoint;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class HouseActivity extends Activity implements View.OnClickListener {

    Button btn_Return;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,BoardNo="";
    //初始化定时器;
    private Timer timer;
    private TimerTask timetask;
    private static int runCount=0;//计数器，超过一定的次数，就刷新数据;
    //媒体播放文件
    private static MediaPlayer mediaPlayer;
    private ProgressDialog waitDialog = null;
    //置值
    int SpaceSec=15;
    private static boolean firstLoad=true;
    //数据内容
    PlaceView placeView,callView;
    JSONArray placeJson,callJson,stateJson,totalJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house);
        //获取登陆参数
        firstLoad=true;
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNO");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        SpaceSec=paramBundle.getInt("SpaceSec");
        CPUID=paramBundle.getString("CPUID");
        BoardNo=paramBundle.getString("BoardNo");
        System.out.println(paramBundle);
        //初始化界面
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        placeView=findViewById(R.id.placeView);
        placeView.imgWidth=1720;
        placeView.imgHeight=980;
        callView=findViewById(R.id.callView);
        callView.imgWidth=280;
        callView.imgHeight=980;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_Return:
                finish();
                break;
            default:
                break;
        }
    }


    //根据Json画方框;
    private void drawPalce(JSONArray paramPlaceJson) {
        //传送到画图类中;
        if (paramPlaceJson!=null) {
            placeView.placeJson = paramPlaceJson;
            if (stateJson != null) placeView.stateJson = stateJson;
            if (totalJson != null) placeView.totalJson = totalJson;
            placeView.requestLayout();//onMeasure（先）及 onLayout();
            placeView.invalidate();//调用onDraw；
        }
    }

    //根据Json画方框;
    private void callPalce(JSONArray paramPlaceJson) {
        //传送到画图类中;
        if (paramPlaceJson!=null) {
            callView.placeJson = paramPlaceJson;
            callView.requestLayout();//onMeasure（先）及 onLayout();
            callView.invalidate();//调用onDraw；
        }
    }

    //启动定时器;
    private void startTimer(){
        //启动计时任务;
        if (waitDialog==null) {
            waitDialog=new ProgressDialog(this);
            waitDialog.setTitle("请稍等");
            waitDialog.setIndeterminate(true);
        }
        //得到Activity的Handler,用于发消息给主Activity;
        int spaceMiSec=SpaceSec*1000;
        if (timer == null) {
            timer = new Timer();
        }
        //定时任务;
        if (timetask == null) {
            timetask = new TimerTask() {
                @Override
                public void run() {
                    //也可发消息，由Handler负责统一调度执行;
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
            timer.schedule(timetask, 1000, spaceMiSec);
        }
        System.out.println("startTimer HouseActivity---------------------------------Start");
    }


    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
        if (waitDialog!=null) waitDialog.dismiss();
        System.out.println("startTimer HouseActivity---------------------------------Start");
    }

    //获取图标数据;
    private void GetPlaceData(){
        try {
            placeJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("HouseActivity--------------------加载图形数据");
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo='" + BoardNo + "',@OperType='HousePlace'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap);
    }

    //获取告警数据;
    private void ReGetData(){
        try {
            callJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.clear();
        paramMap.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo='" + BoardNo + "',@OperType='CallInfo'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap);
    }

    //获取告警数据;
    private void GetStateData(){
        try {
            stateJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.clear();
        paramMap.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo='" + BoardNo + "',@OperType='PlaceState'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap);
    }

    //获取汇总数据;
    private void GetTotalData(){
        try {
            totalJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.clear();
        paramMap.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo='" + BoardNo + "',@OperType='HouseTotal'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap);
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case 1:
                    if (firstLoad==true)
                    {
                        GetPlaceData();
                    } else {
                        runCount++;
                        System.out.println("runCount:" + runCount);
                        ReGetData();
                        if (runCount >= 10) {
                            runCount = 0;
                            System.out.println("获取仓库状态");
                            GetStateData();
                        }
                        if (runCount == 5) {
                            System.out.println("取仓库汇总数");
                            GetTotalData();
                        }
                    }
                    break;
                case 2:
                    //图表加载成功
                    firstLoad=false;
                    //刷新数据;
                    ReGetData();
                    GetStateData();
                    GetTotalData();
                    break;
                default:
                    break;
            }
        }
    };

    public void ReadSQLData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                try {
                    //置参数给对象
                    String namespace="http://tempuri.org/";
                    SoapObject soapObject=new SoapObject(namespace, methodName);
                    SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    //遍列Map数组加参数
                    Map<String,Object> paramMap= (Map<String,Object>) params[0].get("paramMap");
                    Iterator iterator = paramMap.keySet().iterator();
                    while (iterator.hasNext())
                    {
                        String paramkey = (String) iterator.next();
                        String paramvalue = (String) paramMap.get(paramkey);
                        soapObject.addProperty(paramkey,paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                    }
                    //准备执行WebService
                    envelope.dotNet=true;
                    envelope.setOutputSoapObject(soapObject);
                    HttpTransportSE httpTranstation=new HttpTransportSE(serviceUrl);

                    //执行调用WebService;
                    httpTranstation.call(namespace+methodName, envelope);
                    //获取返回会值;
                    Object result=envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr=(String) result.toString();
                    System.out.println(resultstr);
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    e.printStackTrace();
                } catch (SoapFault e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) return;
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    JSONArray jsonArray = new JSONArray(s);
                    //往界面转数据;
                    if (jsonArray.length()>0)
                    {
                        if (jsonArray.optJSONObject(0).has("OperType")==true)
                        {
                            //画库位;
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("HousePlace")==true)
                            {
                                placeJson=jsonArray;
                                drawPalce(placeJson);
                                //发消息，由Handler负责统一调度执行;
                                Message message = new Message();
                                message.what = 2;
                                handler.sendMessage(message);
                            }
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("CallInfo")==true)
                            {
                                callJson=jsonArray;
                                if (callJson.optJSONObject(0).has("PlayWarn")==true)
                                {
                                    System.out.println("播放音乐1！");
                                    if (callJson.optJSONObject(0).getString("PlayWarn").equals("Play")==true) {
                                        playMusic();
                                        System.out.println("播放音乐2！");
                                    }
                                    else
                                        stopMusic();

                                }
                                callPalce(callJson);
                            }
                            //库位状态显示;
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("PlaceState")==true)
                            {
                                stateJson=jsonArray;
                                drawPalce(placeJson);
                            }
                            //汇总显示
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("HouseTotal")==true)
                            {
                                totalJson=jsonArray;
                                drawPalce(placeJson);
                            }
                        }
                    };

                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

        }.execute(params);

    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
        stopMusic();
    }

    @Override
    public void onStart() {
        super.onStart();
        startTimer();
        System.out.println("HouseActivity----onStart");
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
        stopMusic();
        System.out.println("HouseActivity----onPause");
    }

    /**
     * 创建网络mp3
     * @return
     */
    public MediaPlayer createNetMp3(){
        String url=curServiceDir+"/warn.mp3";
        System.out.println("音乐文件地址："+url);
        MediaPlayer mp=new MediaPlayer();
        try {
            mp.setDataSource(url);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (IllegalStateException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return mp;
    }

    //插放音乐;
    private void playMusic(){
        try {
            if(mediaPlayer==null) {
                mediaPlayer = createNetMp3();
                mediaPlayer.setLooping(false);
                //在播放音频资源之前，必须调用Prepare方法完成些准备工作
                mediaPlayer.prepare();
            }
            if(mediaPlayer!=null) {
                if (mediaPlayer.isPlaying()==false) mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止播放音乐
    private  void  stopMusic(){
        if(mediaPlayer!=null){
            mediaPlayer.stop();//停止播放
            mediaPlayer.release();//释放资源
            mediaPlayer=null;
        }
    }
}
